﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Dycox.Validation
{
    [Serializable]
    public class RegexValidator : Validator
    {
        protected internal override ValidationResult IsValid(object value, PropertyValidationContext context)
        {
            if (value == null)
                return ValidationResult.Ignore;
            if (!(value is string))
                throw new InvalidOperationException("RegexValidator can only validate string values.");
            if (string.IsNullOrEmpty(_pattern))
                throw new InvalidOperationException("Pattern property not specified.");

            string input = (string)value;
            Match match = Regex.Match(input, _pattern, _options);
            return (match.Success && match.Value == input) ? ValidationResult.Valid : ValidationResult.Invalid;
        }

        private string _pattern;
        [DefaultValue((string)null)]
        public string Pattern
        {
            get { return _pattern; }
            set { _pattern = value; }
        }

        private RegexOptions _options;
        [DefaultValue(typeof(RegexOptions), "None")]
        public RegexOptions Options
        {
            get { return _options; }
            set { _options = value; }
        }
    }
}
